class_name StateMachine
extends Node



@export var target: CanvasItem
@export var amt_player: AnimationPlayer
@export var amt_tree: AnimationTree
@export var curr_state: State
@export var active: bool = true:
    set(value):
        active = value
        set_process(active)
        set_physics_process(active)
        set_process_unhandled_input(active)
            

var _states_dict: Dictionary


func _ready() -> void:
    # 读取子节点来填充 _states_dict
    # 并初始化状态节点
    for node in get_children():
        if node is not State: continue
        node.switch.connect(_switch_state)
        _states_dict[node.name] = node
        if curr_state == null:
            curr_state = node
    
    _switch_state(curr_state.name)
        

func _process(delta: float) -> void:
    if curr_state == null: return
    curr_state._update(delta)
    

func _physics_process(delta: float) -> void:
    if curr_state == null: return
    curr_state._fixed_update(delta)


func _unhandled_input(event: InputEvent) -> void:
    if curr_state == null: return
    curr_state._input(event)


func _switch_state(next: StringName) -> void:
    if not active || curr_state == null: return
    #if next == curr_state.name: return
    
    curr_state._exit()
    curr_state = _states_dict[next]
    curr_state._enter()
